<template>
  <div>
    <div class="query-content">
      <el-form ref="newFormRef" label-width="100px" :model="newForm">
        <div class="choose_type">
          <div>
            <span class="mr10">With Type</span>
            <el-popover :popper-style="'min-width:120px'" placement="bottom" width="120"
                        :show-arrow="true"
                        trigger="hover"
                        @before-enter="showPopover" @before-leave="hidePopover">
              <template #reference>
                <div>
                  <span class="select-text">{{ newForm.groupVal }}</span>
                  <i style="font-size: 9px;margin-top: 5px;margin-left: 5px" class="iconfont"
                     :class="!state.popover ? 'icon-zhankai2' : 'icon-shouqi3'"></i>
                </div>
              </template>
              <template #default>
                <ul class="ul-container">
                  <li class="menu-li" @click="handleGroupChange">
                    {{ newForm.groupVal === "Resolution" ? "Satellite" : "Resolution" }}
                  </li>
                </ul>
              </template>
            </el-popover>
          </div>
          <span class="moreBtn" @click="showMoreFlag = !showMoreFlag">More+</span>
        </div>
        <div class="sate_list">
          <template v-if="sateList.length > 0">
            <el-checkbox-group v-model="newForm.checkDataList" style="width: 100%">
              <el-checkbox v-for="(item, index) of sateList" :key="index" :label="item.name"
                           @change="checkDataChange($event, index)">
                <span class="max-line" :title="item.name">{{ item.name }}</span>
                <span
                  v-if="newForm.checkDataList.includes(item.name)&&newForm.sateCheckList.length>0"
                  class="icon_count">
                {{ newForm.sateCheckList[index].length }}
              </span>
              </el-checkbox>
            </el-checkbox-group>
          </template>
          <el-empty :image-size="100" v-else description="no Data" style="margin: auto" />
        </div>
        <el-form-item label="Search Area" v-if="fieldNames.includes('geometry')" style="margin-bottom: 25px">
          <div class="search_area">
            <!-- 选择区域 -->
            <div class="area">
              <el-cascader
                v-model="newForm.province"
                :props="properties"
                :options="areaData"
                style="width: 100%"
                placeholder="Please select a region to search for"
                filterable
                clearable
                popper-class="tanchu"
                :filter-method="filterRegion"
                @change="handleChangeArea"
              />
            </div>
            <div class="area">
              <div class="tool-item" @click="handleDraw('Polygon')">
                <span class="icon iconfont icon-duobianxingcaiji"></span>
              </div>
              <div class="tool-item" @click="handleDraw('Rect')">
                <span class="icon iconfont icon-juxingcaiji"></span>
              </div>
              <span>Draw polygon on the map</span>
            </div>
            <div class="uploadbtn area" @click="handleSelectPath">
              <span class="icon iconfont icon-shangchuan"></span>
              <span style="margin-left: 6px">Upload</span>
              <input
                type="file"
                ref="fileRef"
                @input="handleFileInput"
                style="display: none"
                accept=".zip"
              />
            </div>
            <span v-if="newForm.uploadFiles" :title="newForm.uploadFiles">
      {{ newForm.uploadFiles }}
    </span>
            <span v-else>
      Upload shp files for search
      <el-tooltip
        content="please upload a zip file containing files with*. dbf,*.prj,*.shp, and*.shx in the root directory,support MultiPolygon"
        placement="right"
      >
        <span class="icon iconfont icon-wenda"></span>
      </el-tooltip>
    </span>
            <gw3d-draw-tool :multi="multi" ref="drawTool" :brush="brush" :effect="effect" @drawend="drawEnd">
            </gw3d-draw-tool>
          </div>
        </el-form-item>
        <el-form-item label="Transit Time" v-if="fieldNames.includes('scenetime')">
          <el-date-picker style="width: 100%" class="w100" v-model="newForm.scenetime" type="daterange"
                          range-separator="To"
                          start-placeholder="Start month" end-placeholder="End month"
                          value-format="yyyy-MM-dd hh:mm:ss" />
        </el-form-item>
      </el-form>
    </div>

    <!-- 高级参数 -->
    <div class="more_param" :class="showMoreFlag ? 'slide-out-left' : 'fade-in-left'">
      <div v-for="(item, index) of sateList" :key="index">
        <div v-if="newForm.checkDataList.includes(item.name)" class="checkList">
          <span class="spanLabel">{{ item.name }}</span>
          <CheckGroup :ref="(el) => handleSetInputMap(el, index)" :group="item.children"
                      v-model="newForm.sateCheckList[index]"
                      :currentIndex="index"
                      :checked="newForm.sateCheckList[index]"
                      @changeGroup="changeGroup" />
        </div>
      </div>

      <div class="opt">
        <span class="icon iconfont icon-quanxuan" @click="handleCheckedAll"></span>
        <span class="icon iconfont icon-shanchu" @click="showMoreFlag = false"></span>
        <span class="icon iconfont icon-queding" @click="showMoreFlag = false"></span>
      </div>
    </div>

  </div>
</template>
<script>
import { addDays, format } from "date-fns";
import CheckGroup from "./cpns/checkGroup.vue";
import { getFieldById, getGroups, getRegionShape, getShapeByFile } from "@/api/myData";
import { getNationRegion } from "@/api/region";
import WKT from "terraformer-wkt-parser";

export default {
  inject: ["clearRegionLayer", "addGeometry", "showLeft", "loadFormData"],
  emits: ["search"],
  components: {
    CheckGroup
  },

  data() {
    return {
      state: {
        value: "Resolution",
        popover: false
      },
      showMoreFlag: false,
      labelFields: {
        cloud: "Cloud Cover",
        slideslip_angles: "Sideslip Angles",
        pitch_angles: "Pitch Angle"
      },
      fields: [],
      suppliers: [],
      sateList: [],
      inputRefMap: {},
      // newForm:{},

      properties: {
        label: "name",
        value: "code",
        children: "arrayList",
        checkStrictly: true
      },
      areaData: [],
      brush: {
        fill: "rgba(247, 0, 58,0)",
        stroke: {
          color: "rgb(247, 0, 58)",
          width: 2
        },
        circle: {
          radius: 8,
          fill: "rgba(247, 0, 58,0)",
          stroke: {
            width: 2,
            color: "rgb(247, 0, 58)"
          }
        }
      },

      effect: {
        fill: "rgba(247, 0, 58,0)",
        stroke: {
          color: "rgb(247, 0, 58)",
          width: 2
        },
        circle: {
          radius: 8,
          fill: "rgba(247, 0, 58,0)",
          stroke: {
            width: 2,
            color: "rgb(247, 0, 58)"
          }
        }
      },
      multi: true
    };
  },
  watch: {
    "showLeft"(newval) {
      if (!newval) this.showMoreFlag = false;
    },
    newForm(newval) {
      if (newval) {
        this.$emit("changeFormData", newval);
      }
    }

  },
  props: {
    nodeType: {
      type: String,
      default: () => ("")
    },
    collapseData: {
      type: Array,
      default: () => ([])
    },
    activeNames: {
      type: String,
      default: () => ("")
    },
    newForms: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    newForm: {
      get() {
        return this.newForms;
      },
      set(value) {

      }
    },
    fieldNames() {
      return this.fields.map(item => item.name);
    },
    searchData() {
      return this.$store.getters.getSearchData;
    }
  },
  created() {
    this.setTime();
  },
  mounted() {
    this.getInit();
  },
  methods: {
    currentItem() {
      const collapseData = JSON.parse(localStorage.getItem("collapseData"));
      return collapseData.find(item => item.id == this.activeNames);
    },
    getInit(flag = false) {
      this.getPage(flag);
    },
    setTime() {
      const currentItem = this.currentItem();
      if (Object.keys(currentItem).length > 0 && currentItem.newForm.scenetime.length > 0) {
        this.newForm.scenetime = currentItem.newForm.scenetime;
      } else {
        this.newForm.scenetime = [format(new Date(), "yyyy-MM-dd hh:mm:ss"), format(addDays(new Date(), 2), "yyyy-MM-dd hh:mm:ss")];

      }

    },
    async handleGroupChange() {
      this.newForm.groupVal = this.newForm.groupVal === "Resolution" ? "Satellite" : "Resolution";
      this.newForm.groupType = this.newForm.groupVal.toLocaleLowerCase();
      await this.getPage(true);

    },
    showPopover() {
      this.state.popover = true;
    },
    hidePopover() {
      this.state.popover = false;
    },
    /**
     * 如果传三级传感器， 需要传 ${卫星}_${传感器}， 传感器部分暂时隐藏，按需设置
     */
    addAttr(data, field) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children && data[i].children.length >= 0) {
          data[i].value = data[i].name;
        } else {
          data[i].value = `${field}${data[i].name}`;
        }
        if (data[i].children && data[i].children.length > 0) {
          this.addAttr(data[i].children, `${data[i].name}_`);
        }
      }
      return data;
    },
    async getAllSate(flag) {
      const currentItem = this.currentItem();
      const nodeType = currentItem.nodeType || "";
      let GroupType = "";
      const ss = this.newForm.groupVal.toLocaleLowerCase();
      ss === "resolution" ? GroupType = "RESOLUTION" : GroupType = "SATELLITE";
      const res = await getGroups(GroupType, nodeType);
      const sate = this.addAttr(res);
      if (!res) {
        this.sateList = [];
        return;
      }
      this.sateList = sate;
      sessionStorage.setItem("sateList", JSON.stringify(sate));
      await this.addCache(flag);
    },
    getStateList() {
      const state = JSON.parse(sessionStorage.getItem("sateList")) || [];
      if (state && state.length > 0) {
        this.sateList = state;
      }

    },
    handleCheckChange(index, flag) {
      this.$nextTick(() => {
        if (this.inputRefMap[`ref_${index}`]) {
          this.newForm.sateCheckList[index] = [];
          this.inputRefMap[`ref_${index}`].checkedAllChange(true);
          this.newForm.sateCheckList[index] = this.inputRefMap[`ref_${index}`].checkedList;
          this.newForm.satellite = this.mergeInnerArrays(this.newForm.sateCheckList);
          this.getStateList(flag);
        }
      });

    },
    handleSetInputMap(el, index) {
      if (el !== null) {
        this.inputRefMap[`ref_${index}`] = el;
      }
    },
    changeGroup(val, currentIndex) {
      this.newForm.sateCheckList[currentIndex] = [];
      this.newForm.sateCheckList[currentIndex].push(...val);
      this.newForm.satellite = val;
      this.getStateList(true);
    },
    /**
     * 全选高级参数
     * */
    handleCheckedAll() {
      const isNotCheck = Object.keys(this.inputRefMap).some(
        (key) => !this.inputRefMap[key].isCheckedAll
      );
      for (const key in this.inputRefMap) {
        this.inputRefMap[key].checkedAllChange(isNotCheck);
      }
      Object.keys(this.inputRefMap).forEach((item, index) => {
        if (isNotCheck) {
          this.newForm.sateCheckList[index] = this.inputRefMap[`ref_${index}`].checkedList;
          this.newForm.satellite = this.inputRefMap[`ref_${index}`].checkedList;
        } else {
          this.newForm.sateCheckList[index] = [];
          this.newForm.satellite = [];

        }
        const state = JSON.parse(sessionStorage.getItem("sateList")) || [];
        if (state && state.length > 0) {
          this.sateList = state;
        }
      });

    },

    /**
     * */
    /**
     * 取消选择， 同时取消选择 下级选框
     * */
    checkDataChange(el, index) {
      if (!el) {
        this.newForm.sateCheckList[index] = [];
        this.newForm.satellite = this.mergeInnerArrays(this.newForm.sateCheckList);
      } else {
        this.handleCheckChange(index, true);
      }

    },
    mergeInnerArrays(arrays) {
      return arrays.reduce((acc, curr) => {
        return acc.concat(curr);
      });
    },
    async addCache(flag) {
      const currentItem = this.currentItem();
      const len = Object.keys(currentItem).length;
      if (len > 0) {
        if (currentItem) {
          this.newForm = currentItem.newForm;
          if (flag) {
            currentItem.newForm.checkDataList = [];
          }
          if (currentItem.newForm.checkDataList.length === 0) {
            this.newForm.checkDataList = this.sateList.slice(0, 1).map(item => item.name);
            this.newForm.sateCheckList = Array(this.sateList.length).fill().map(() => [].fill([]));
            this.handleCheckedAll();
            this.handleCheckChange(0, true);
          }
          this.updateFormWithMatchedData();
        }

      }
    },
    updateFormWithMatchedData() {
      const currentItem = this.currentItem();
      const newData = currentItem.newForm;
      this.newForm.province = newData.province;
      this.newForm.geometry = newData.geometry;
      this.newForm.uploadFiles = newData.uploadFiles;
      if (this.newForm.geometry) {
        this.clearDrawPaint();
        this.addGeometry(WKT.parse(this.newForm.geometry));
      }
    },
    filterRegion(node, key) {
      return node.text.toLowerCase().includes(key.toLowerCase());
    },
    /**
     * 行政区改变
     * */
    async handleChangeArea(item) {
      console.log(item);
      this.drawClean();
      this.newForm.province = Array.from(item);
      if (this.newForm.province.length > 0) {
        const code = item.slice(-1)[0];
        const res = await getRegionShape(code);
        if (res) {
          const shape = res.shape;
          this.drawWktData(shape);
          this.newForm.geometry = shape;
          this.getGeoData(this.newForm);
        }
      }


    },
    handleSelectPath() {
      this.drawClean();
      //待测试
      this.$refs.fileRef.click();
    },
    async handleFileInput(event) {
      const file = event.target.files[0];
      this.newForm.uploadFiles = file.name;
      const data = new FormData();
      data.append("file", file);
      const res = await getShapeByFile(data);
      const shape = res[0];
      this.drawWktData(shape);
      this.newForm.geometry = shape;
      this.getGeoData(this.newForm);
    },
    drawEnd(event, coordinates, geojson) {
      let coors = geojson.geometry.coordinates;
      coors[0].push(coors[0][0]);
      geojson.geometry.coordinates = [coors];
      geojson.geometry.type = "MultiPolygon";
      this.newForm.geometry = WKT.convert(geojson.geometry);
      this.getGeoData(this.newForm);
    },
    getGeoData(data) {
      if (this.activeNames) {
        const collapseData = this.getCollapseDataFromLocalStorage();
        const currentIndex = collapseData.findIndex(item => item.id === this.activeNames);
        if (currentIndex > -1) {
          collapseData[currentIndex].newForm.province = data.province;
          collapseData[currentIndex].newForm.uploadFiles = data.uploadFiles;
          collapseData[currentIndex].newForm.geometry = data.geometry;
        }
      }
    },
    getCollapseDataFromLocalStorage() {
      const collapseDataStr = localStorage.getItem("collapseData");
      return collapseDataStr ? JSON.parse(collapseDataStr) : [];
    },
    handleDraw(type) {
      this.drawClean();
      this.$refs.drawTool.draw(type);
    },
    drawWktData(data) {
      this.addGeometry(WKT.parse(data));

    },
    drawClean() {
      this.newForm.province = "";
      this.newForm.uploadFiles = "";
      if (this.$refs.fileRef) {
        this.$refs.fileRef.value = "";
      }
      this.newForm.geometry = "";
      this.$refs.drawTool && this.$refs.drawTool.dispose();
      this.$refs.drawTool && this.$refs.drawTool.clear();
      this.clearRegionLayer();
    },
    clearDrawPaint() {
      this.clearRegionLayer();
      this.$refs.drawTool && this.$refs.drawTool.dispose();
      this.$refs.drawTool && this.$refs.drawTool.clear();
    },
    /**
     * 获取卫星列表和配置参数
     * */
    async getAreaJSON() {
      let areaJSON = JSON.parse(sessionStorage.getItem("areaData")) || [];
      if (areaJSON.length > 0) {
        this.areaData = areaJSON;
      } else {
        const data = await getNationRegion();
        if (data) {
          this.areaData = data;
          sessionStorage.setItem("areaData", JSON.stringify(this.areaData));
        }
      }
    },
    async getPage(flag) {
      await this.getAreaJSON();
      const res = await getFieldById("1");
      this.fields = res.fields;
      await this.getAllSate(flag);
    }
  }

};
</script>
<style lang="scss" scoped>
.query-content {
  height: 100%;
  box-sizing: border-box;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: auto;

  .choose_type {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;

    .select-text {
      text-decoration: underline;
      color: #2d8cf0;
      cursor: pointer;
    }

    div {
      display: flex;
      align-items: center;
    }
  }

  .sate_list {
    margin-bottom: 25px;
    max-height: 260px;
    overflow-y: auto;

    .icon_count {
      display: inline-block;
      color: #ffd675;
      font-size: 12px;
      padding: 6px 10px;
      border-radius: 3px;
      background: #34353b;
      margin-left: 10px;
      position: relative;

      &::before {
        position: absolute;
        width: 4px;
        height: 4px;
        z-index: 0;
        content: ' ';
        transform: translateY(-50%) rotate(45deg);
        left: -2px;
        top: 50%;
        background: #34353b;
        box-sizing: border-box;
      }
    }
  }

  :deep(.el-form-item__label) {
    justify-content: flex-start;
  }
}

.el-checkbox {
  width: 100%;
  margin: 8px 0;
}

.more_param {
  position: fixed;
  top: 18px;
  min-width: 780px;
  max-width: 60%;
  max-height: calc(100% - 42px);
  overflow: auto;
  box-sizing: border-box;
  padding: 18px;
  color: aliceblue;
  background: #1f222a;
  box-shadow: 0px 2px 12px 0px rgba(3, 7, 18, 0.6);
  border-radius: 4px;
  border: 1px solid;
  border-image: linear-gradient(270deg,
    rgba(83, 95, 123, 1),
    rgba(164, 180, 217, 1),
    rgba(83, 95, 123, 1)) 1 1;
  transition: all 0.5s;

  .channels {
    height: 52px;
    width: 100%;
    margin: -18px -18px 18px;
    background: linear-gradient(180deg, rgba(44, 45, 50, 0) 0%, #2c2d32 100%);
    border-radius: 4px 4px 0px 0px;
    padding: 0 18px;
    display: inline-flex;
    align-items: center;

    > span {
      &:first-child {
        margin-right: 20px;
      }

      &:last-child {
        color: #ffd675;
        font-size: 12px;
      }
    }
  }
}

.fade-in-left {
  transition: all 0.5s ease-out;
  left: 0;
  opacity: 0;
  z-index: -1;
  transform: translateX(-100%);
}

.slide-out-left {
  transition: all 0.5s ease-in;
  left: 480px;
  opacity: 1;
  z-index: 0;
}

.opt {
  height: 50px;
  margin: 18px -18px -18px;
  padding: 0 18px;
  background: #071019;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  position: sticky;
  bottom: -18px;
  z-index: 9;

  > .iconfont {
    font-size: 28px;
    margin-left: 30px;
    cursor: pointer;
  }
}

.ul-container {
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  list-style: none;

  .menu-li {
    height: 28px;
    line-height: 28px;
    text-align: center;
  }

  .menu-li:hover {
    cursor: pointer;
    color: #4099ff;
  }

  .active {
    color: #4099ff;
  }
}

:deep(.custom-dot) {
  width: 100%;
  height: 100%;
  background: #FFFFFF;
  border-radius: 2px;
  border: 2px solid #00A8FF;
  transition: all .3s;
  font-family: Pangm;
  box-sizing: border-box;

  font-family: PangMenZhengDao;
  font-size: 10px;
  font-weight: bold;
  color: #006CA0;
  text-align: center;
  line-height: 14px;
}

.max-line {
  display: inline-block;
  width: 300px; /* 根据需要设置宽度 */
  white-space: nowrap; /* 对于单行文本 */
  overflow: hidden;
  text-overflow: ellipsis; /* 显示省略号 */
}

// .custom-dot:hover {
//   transform: rotateZ(15deg);
// }

// .custom-dot.focus {
//   border-radius: 50%;
// }

:deep(.vue-slider-rail) {
  background-color: #071019;
}

.checkList {
  display: flex;

  .spanLabel {
    display: inline-block;
    width: 300px;

  }
}

.search_area {
  width: 100%;
  font-size: 12px;
  color: #fff;

  .area {
    display: flex;
    align-items: center;
    margin-bottom: 18px;

  }

  .tanchu {
    color: aquamarine;
  }

  .tool-item {
    display: inline-flex;
    justify-content: center;
    align-items: center;
    width: 30px;
    height: 30px;
    margin-right: 8px;
    background-color: var(--el-fill-color-blank);
    border-radius: 4px;
    border: 1px solid #787878;
    cursor: pointer;

    > .icon-duobianxingcaiji {
      font-size: 18px;
    }

    &:hover {
      color: #409eff;
    }
  }

  .uploadbtn {
    height: 32px;
    padding: 0 5px;
    display: inline-flex;
    justify-content: center;
    margin-right: 8px;
    background-color: #515663;
    box-shadow: 2px 0px 4px 0px rgba(5, 11, 30, 0.4);
    border-radius: 4px;
    color: #fff;
    border: 1px solid #787878;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}

.moreBtn {
  font-weight: 400;
  font-size: 14px;
  color: #00A8FF;
  cursor: pointer;
  text-decoration: underline;
}

:deep(.el-input__inner,.el-radio__inner, .el-date-editor .el-range-input) {
  background: #18191E;
}


</style>
